<?php

namespace App\Resource\Repository;

use App\Resource\Model\GoodsListModel;
use App\Resource\Model\GoodsModel;
use App\Third\Model\ShopLsyGoodsStockModel;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;

class GoodsRepository implements BaseRepositoryInterface
{

    /**
     * 主表查询
     * @param array $where
     * @param array $field
     * @param bool $isArray
     * @return array|Builder|Model|null|object
     * @author zhangzhiyuan
     */
    public function findFirst(array $field = ['*'],array $where = [],string $whereRaw='',bool $isArray=true)
    {
        $connect = GoodsModel::query()->select($field)->where($where)
            ->when($whereRaw, function ($query, $whereRaw) {
                return $query->whereRaw($whereRaw);
            })
            ->first();
        if($isArray) return empty($connect) ? array():$connect->toArray();
        return $connect;
    }

    /**
     * 子表查询
     * @param array $where
     * @param array $field
     * @param bool $isArray
     * @return array|Builder|Model|null|object
     * @author zhangzhiyuan
     */
    public function findSonFirst(array $field = ['*'],array $where = [],string $whereRaw='',bool $isArray=true)
    {
        $connect = GoodsListModel::query()->select($field)->where($where)
            ->when($whereRaw, function ($query, $whereRaw) {
                return $query->whereRaw($whereRaw);
            })
            ->first();
        if($isArray) return empty($connect) ? array():$connect->toArray();
        return $connect;
    }

    /**
     * 主表查询多条
     * @param array $where
     * @param array|string[] $field
     * @param bool $isArray
     * @return array|Builder|Model|object|null
     * @author zhangzhiyuan
     */
    public function selectList(array $field,array $where,string $whereRaw,array $whereIn,array $whereNotIn,int $page,int $limit,array $orderBy,bool $isArray=true)
    {
        $connect = GoodsModel::query()->select($field)->where($where)
            ->when($whereRaw, function ($query, $whereRaw) {
                return $query->whereRaw($whereRaw);
            })
            ->when($whereNotIn, function ($query, $whereNotIn) {
                return $query->whereNotIn($whereNotIn[0],$whereNotIn[1]);
            })
            ->when($whereIn, function ($query, $whereIn) {
                return $query->whereIn($whereIn[0],$whereIn[1]);
            })->orderBy($orderBy[0],$orderBy[1])->forPage($page, $limit)->get();
        if($isArray) return empty($connect) ? array():$connect->toArray();
        return $connect;
    }

    /**
     * 主表查询多条
     * @param array $where
     * @param array|string[] $field
     * @param bool $isArray
     * @return array|Builder|Model|object|null
     * @author zhangzhiyuan
     */
    public function selectMoreUnionList(array $primaryField,array $sonField,array $condition,int $page,int $limit,array $orderBy,bool $isPage=true,bool $isArray=true)
    {
        $lsyStock=(new ShopLsyGoodsStockModel())->getTable();
        $lsyStockDataBaseName=config('databases.'.(new ShopLsyGoodsStockModel())->getConnectionName())['database'].'.'.$lsyStock;
        $lsyStockQuery =ShopLsyGoodsStockModel::query()->from("{$lsyStockDataBaseName}")->select(['itemId','surplusQuantity'])->where($condition['unionWhere']);
        $goods =(new GoodsModel())->getTable();
        $goodsList =(new GoodsListModel())->getTable();
        $primaryField =array_map(function ($item) use ($goods) {
            return $goods.'.'.$item;
        },$primaryField);
        $sonField =array_map(function ($item) use ($goodsList) {
            return $goodsList.'.'.$item;
        },$sonField);
        $connect = GoodsModel::query()->from("{$goods}")
            ->select(array_merge($primaryField,$sonField))
            ->leftJoinSub($lsyStockQuery,$lsyStock,function ($join) use ($goods,$lsyStock){
                $join->on($goods.'.goods_crm_code','=',$lsyStock.'.itemId');
            })
            ->leftJoin("{$goodsList}", $goods.'.id', '=', $goodsList.'.goods_id')
            ->when($condition['where']??[], function ($query) use ($condition){
                return $query->where($condition['where']);
            })
            ->when($condition['whereOp']??[], function ($query) use ($condition){
                return $query->where($condition['whereOp']);
            })
            ->when($condition['whereRaw']??'', function ($query) use($condition){
                return $query->whereRaw($condition['whereRaw']);
            })
            ->when($condition['whereNotIn']??[], function ($query) use($condition) {
                return $query->whereNotIn($condition['whereNotIn'][0],$condition['whereNotIn'][1]);
            })
            ->when($condition['whereIn']??[], function ($query) use($condition) {
                return $query->whereIn($condition['whereIn'][0],$condition['whereIn'][1]);
            })
            ->when($orderBy, function ($query, $orderBy){
                return $query->orderBy($orderBy[0],$orderBy[1]);
            }, function ($query) use ($goods) {
                return $query->orderBy($goods.'.sort','desc');
            }) ->orderBy($lsyStock.'.surplusQuantity', 'desc');
        if($isPage){
            if($isArray) return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->forPage($page, $limit)->get()->toArray()];
            return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->forPage($page, $limit)->get()];
        }
        if($isArray) return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->get()->toArray()];
        return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->get()];
    }

    /**
     * 主表查询多条
     * @param array $where
     * @param array|string[] $field
     * @param bool $isArray
     * @return array|Builder|Model|object|null
     * @author zhangzhiyuan
     */
    public function selectUnionList(array $primaryField,array $sonField,array $condition,int $page,int $limit,array $orderBy,bool $isPage=true,bool $isArray=true)
    {
        $goods =(new GoodsModel())->getTable();
        $goodsList =(new GoodsListModel())->getTable();
        $primaryField =array_map(function ($item) use ($goods) {
            return $goods.'.'.$item;
        },$primaryField);
        $sonField =array_map(function ($item) use ($goodsList) {
            return $goodsList.'.'.$item;
        },$sonField);
        $connect = GoodsModel::query()->from("{$goods}")
            ->select(array_merge($primaryField,$sonField))
            ->leftJoin("{$goodsList}", $goods.'.id', '=', $goodsList.'.goods_id')
            ->when($condition['where']??[], function ($query) use ($condition){
                return $query->where($condition['where']);
            })
            ->when($condition['whereOp']??[], function ($query) use ($condition){
                return $query->where($condition['whereOp']);
            })
            ->when($condition['whereRaw']??'', function ($query) use($condition){
                return $query->whereRaw($condition['whereRaw']);
            })
            ->when($condition['whereNotIn']??[], function ($query) use($condition) {
                return $query->whereNotIn($condition['whereNotIn'][0],$condition['whereNotIn'][1]);
            })
            ->when($condition['whereIn']??[], function ($query) use($condition) {
                return $query->whereIn($condition['whereIn'][0],$condition['whereIn'][1]);
            })
            ->when($orderBy, function ($query, $orderBy){
                return $query->orderBy($orderBy[0],$orderBy[1]);
            }, function ($query) use ($goods) {
                return $query->orderBy($goods.'.sort','desc');
            });
        if($isPage){
            if($isArray) return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->forPage($page, $limit)->get()->toArray()];
            return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->forPage($page, $limit)->get()];
        }
        if($isArray) return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->get()->toArray()];
        return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->get()];
    }
    /**
     * 根据主键ID主表子表两表联查获取数据
     * @param int $PrimaryId
     * @param array $PrimaryField
     * @param array $SonField
     * @return array|Builder|Model|\Hyperf\Database\Query\Builder|object
     */
    public function getResourceSingleSonByPrimaryId(int $primaryId, array $primaryField=['*'], array $sonField=['*'],bool $isArray=true)
    {
        $goods =(new GoodsModel())->getTable();
        $goodsList =(new GoodsListModel())->getTable();
        $primaryField =array_map(function ($item) use ($goods) {
            return $goods.'.'.$item;
        },$primaryField);
        $sonField =array_map(function ($item) use ($goodsList) {
            return $goodsList.'.'.$item;
        },$sonField);
        $connect = GoodsModel::query()->from("{$goods}")
            ->select(array_merge($primaryField,$sonField))
            ->leftJoin("{$goodsList}", $goods.'.id', '=', $goodsList.'.goods_id')
            ->where($goods.'.id', $primaryId)
            ->first();
        if($isArray) return empty($connect) ? array():$connect->toArray();
        return $connect;
    }

    public function selectWhereRawList()
    {
        // TODO: Implement SelectWhereRawList() method.
    }
}